package com.lancoo.klgcourseware.ui.fragment.pronounceTrain;

import android.graphics.Typeface;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.lzyzsd.circleprogress.DonutProgress;
import com.lancoo.klgcourseware.R;
import com.lancoo.klgcourseware.entity.bean.SpellCharacterBean;
import com.lancoo.klgcourseware.ui.adapter.SlowCharacterAdapter;
import com.lancoo.klgcourseware.ui.widget.CountTimeView;
import com.lancoo.klgcourseware.utils.UniCodeUtils;
import com.stkouyu.entity.LgEvaluateObj;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by pengmi on 2019/8/21 20:40
 * Description:发音训练-慢速跟读
 */
public class PronounceSlowRepeatTrainFragment extends  PronounceBaseFragment{


    private static final String TAG = "PronounceSlowRepeatTrai";
    private List<SpellCharacterBean> slowCharacterBeans,slowTimeBeans;
    private final int TOTALTIME_SLOWTRAIN=3000;
    private RecyclerView recyclerView;
    private SlowCharacterAdapter mAdapter;
    private LinearLayout ll_soundTrack;
    private TextView tv_repeatTime,tv_alert,tv_giveUpTrain;
    private RelativeLayout rl_recorder,rl_countTime;
    private DonutProgress donutProgress;
    private int slowTrainIndex,slowScore;
    private String slowRecordUrl;
    private boolean isRecordState;//录音作答流程
    private CountTimeView countTimeView;
    private ImageView img_completeLogo;


    @Override
    protected int getContentViewId() {
        return R.layout.klg_fragment_pronounce_slow_repeat_train;
    }

    @Override
    protected void initView(View view) {
        splitData();
        recyclerView = view.findViewById(R.id.recycler_view_slow);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayout.HORIZONTAL,false));
        mAdapter = new SlowCharacterAdapter(getContext(),slowCharacterBeans,1);
        recyclerView.setAdapter(mAdapter);
        TextView tv_syllableSlow = view.findViewById(R.id.tv_syllable_slow);
        tv_syllableSlow.setText(UniCodeUtils.convertToChinese(wordArticulation.getUS_phonetic()));

        ll_soundTrack = view.findViewById(R.id.ll_sound_track);
        ImageView img_track01 = view.findViewById(R.id.img_track01);
        ImageView img_track02 = view.findViewById(R.id.img_track02);
        ImageView img_track03 = view.findViewById(R.id.img_track03);
        ImageView img_track04 = view.findViewById(R.id.img_track04);
//        ImageView img_recorder = view.findViewById(R.id.img_recorder);
        volumeAnimationControl(img_track01,true);
        volumeAnimationControl(img_track02,true);
        volumeAnimationControl(img_track03,true);
        volumeAnimationControl(img_track04,true);
//        volumeAnimationControl(img_recorder,true);
        tv_repeatTime = view.findViewById(R.id.tv_repeat_time);
        rl_recorder = view.findViewById(R.id.rl_recorder);
        img_pause=view.findViewById(R.id.img_pause);
        donutProgress = view.findViewById(R.id.donut_progress);
        donutProgress.setMax(TOTALTIME_SLOWTRAIN);
        rl_countTime = view.findViewById(R.id.rl_count_time);
        countTimeView = view.findViewById(R.id.counttime_view);
        img_completeLogo = view.findViewById(R.id.img_complete_logo);
        tv_alert = view.findViewById(R.id.tv_spell_memory_write_alert);
        tv_giveUpTrain = view.findViewById(R.id.tv_pass_train);
        tv_giveUpTrain.setVisibility(View.INVISIBLE);
        tv_giveUpTrain.setOnClickListener(this);
        resetSlowRepeatTrainStyle();
        try{
            Typeface typeFace = Typeface.createFromAsset(getContext().getAssets(), "klg_droid_sans_bold.ttf");
            tv_syllableSlow.setTypeface(typeFace);
        }catch (Exception e){

        }

    }


    /**
     * 数据组装
     */
    private void splitData(){
        slowCharacterBeans = new ArrayList<>();
        slowTimeBeans=new ArrayList<>();
        //慢速环节数据组装
        String[] split =  wordArticulation.getSyllable().split("·");
        int index=-1;
        for (int i = 0; i <split.length; i++) {
            int length=split[i].length();
            index+=length;
            int time=TOTALTIME_SLOWTRAIN*(i+1)/split.length;
            SpellCharacterBean spellCharacterBean=new SpellCharacterBean();
            spellCharacterBean.setCharacter(split[i]);
            spellCharacterBean.setEndIndex(index);
            spellCharacterBean.setTimeLength(time);
            slowTimeBeans.add(spellCharacterBean);
            index+=1;
        }
        for (int i = 0; i < wordArticulation.getSyllable().length(); i++) {
            SpellCharacterBean slowCharacterBean=new SpellCharacterBean();
            slowCharacterBean.setCharacter(wordArticulation.getSyllable().substring(i,i+1));
            slowCharacterBeans.add(slowCharacterBean);
        }
    }

    /**
     * 重置发音跟读训练样式
     */
    private void resetSlowRepeatTrainStyle(){
        if(rl_recorder==null){
            return;
        }
        isRecordState=false;
        rl_recorder.setVisibility(View.GONE);
        donutProgress.setProgress(0);
        tv_repeatTime.setVisibility(View.GONE);
        ll_soundTrack.setVisibility(View.GONE);
        donutProgress.setVisibility(View.VISIBLE);
        slowTrainIndex=0;
        mAdapter.changeRepeat(-1);
        img_pause.setVisibility(View.GONE);
        rl_countTime.setVisibility(View.GONE);
        tv_alert.setText(R.string.klg_start_repeat_train_alert);

    }

    /**
     * 更新录音进度
     * @param recordProgress
     */
    protected void upDateRecordAnswerProgress(int recordProgress){
        if(donutProgress!=null){
            donutProgress.setProgress(recordProgress);
        }
        if(slowTrainIndex>0&&slowTrainIndex<slowTimeBeans.size()&&recordProgress>slowTimeBeans.get(slowTrainIndex-1).getTimeLength()){
            Log.e("aaaaa","慢速朗读...."+slowTimeBeans.get(slowTrainIndex).getEndIndex());
            mAdapter.changeRepeat(slowTimeBeans.get(slowTrainIndex).getEndIndex());
            scrollIndex(recyclerView,slowTimeBeans.get(slowTrainIndex).getEndIndex(),wordArticulation.getSyllable().length(),true);
            slowTrainIndex++;
        }
        if(recordProgress>=TOTALTIME_SLOWTRAIN){
            stopRecordSpeechEvaluation();
        }


    }

    /**
     * 更新系统跟读进度
     */
    protected void upDateRepeatProgress(int time){
        if(tv_repeatTime==null){
            return;
        }
        if(time==0){//进入录音作答环境
            isRecordState=true;
            tv_repeatTime.setVisibility(View.GONE);
            ll_soundTrack.setVisibility(View.GONE);
            rl_recorder.setVisibility(View.VISIBLE);
            if(slowTimeBeans!=null&&slowTimeBeans.size()>0){
                mAdapter.changeRepeat(slowTimeBeans.get(0).getEndIndex());
            }
            slowTrainIndex++;
            startRecordSpeechEvaluation("",wordArticulation.getKlgName());
            return;
        }
        String repeatString=String.format(getString(R.string.klg_repeat_time_count),time);
        SpannableString spannableString=new SpannableString(repeatString);
        spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.klg_high_list_color)),2,3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv_repeatTime.setText(spannableString);

    }

    protected void startSubModelTrain(){
        if(ll_soundTrack==null){
            return;
        }
        ll_soundTrack.setVisibility(View.VISIBLE);
        tv_repeatTime.setVisibility(View.VISIBLE);
        upDateRepeatProgress(3);
    }


    /**
     * 评测正常
     * @param grade
     * @param url
     * @param skegnResult
     */
    protected void onSuccessSpeechEvaluation(int grade, String url, LgEvaluateObj skegnResult){
        slowScore=grade;
        slowRecordUrl=url;
        resetSlowRepeatTrainStyle();
        enterPronunceRepeatNextTrain(slowScore,slowRecordUrl);
    }

    /**
     * 继续发音训练
     */
    protected void continueTrain(){
        if(isRecordState){//直接进入录音环境
            slowTrainIndex=0;
            img_pause.setVisibility(View.GONE);
            donutProgress.setProgress(0);
            donutProgress.setVisibility(View.VISIBLE);
            mAdapter.changeRepeat(-1);
            upDateRepeatProgress(0);
        }else{//系统慢速跟读环节
            resetSlowRepeatTrainStyle();
            tv_repeatTime.setVisibility(View.VISIBLE);
            ll_soundTrack.setVisibility(View.VISIBLE);
            upDateRepeatProgress(3);
            startDripMusic();
        }
    }

    protected void pauseTrain(boolean isReset){
        if(isReset){
            resetSlowRepeatTrainStyle();
        }else {
            if(img_pause!=null){
                img_pause.setVisibility(View.VISIBLE);
                donutProgress.setVisibility(View.INVISIBLE);
                rl_recorder.setVisibility(View.VISIBLE);
                tv_repeatTime.setVisibility(View.GONE);
                ll_soundTrack.setVisibility(View.GONE);
                rl_countTime.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 3，2，1s倒计时进度更新
     * @param progress
     * @param totalProgress
     */
    protected void updateCountTime(int progress,int totalProgress){
        if(rl_countTime!=null){
            rl_countTime.setVisibility(progress>=totalProgress?View.GONE:View.VISIBLE);
            countTimeView.setAngle(progress,totalProgress);
        }
    }

    /**
     * 作答结束2s倒计时
     * @param progress
     * @param totalProgress
     */
    protected void updateResultCountTime(int progress,int totalProgress){
        if(countTimeView==null){
            return;
        }
        countTimeView.setAngle(progress,totalProgress);
//        rl_recorder.setVisibility(progress>=totalProgress?View.GONE:View.VISIBLE);
        if(progress==totalProgress){
//            Log.e("aaaa","暂停。。。。"+isQuality);
//            if(!isQuality){//不合格 进入跟读训练界面
////                resetSpellTrainStyle();
////                enableStartTrain(0);
//                enterPronunceRepeatNextTrain(totalScore,null);
//            }else{
////                enterNextTrainModel();
//            }
        }
    }

}
